package ThreadDemo;

import java.util.concurrent.Semaphore;

/**
 * semaphore计数信号量用法
 */
public class TreadDemo17 {
    public static void main(String[] args) {
        //一次只能用四个线程跑，当值为一时，就可以当作一个锁了
        Semaphore semaphore=new Semaphore(4);
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                try {
                    //准备申请资源
                    System.out.println("准备申请资源");
                    semaphore.acquire();
                    //资源申请成功
                    System.out.println("资源申请成功");
                    Thread.sleep(1000);
                    //释放资源成功
                    System.out.println("释放资源完毕");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        for (int i = 0; i < 20; i++) {
            Thread thread=new Thread(runnable);
            thread.start();
        }

    }
}
